package com.example.ywr.repository;

import com.example.ywr.entity.User;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Optional;

/**
 * 用户数据访问层
 */
@Repository
public interface UserRepository extends JpaRepository<User, Long> {

    /**
     * 根据用户名查询用户
     */
    Optional<User> findByUsernameAndIsDeletedFalse(String username);

    /**
     * 根据手机号查询用户
     */
    Optional<User> findByPhoneAndIsDeletedFalse(String phone);

    /**
     * 根据邮箱查询用户
     */
    Optional<User> findByEmailAndIsDeletedFalse(String email);

    /**
     * 根据用户名或手机号或邮箱查询用户
     */
    Optional<User> findByUsernameOrPhoneOrEmailAndIsDeletedFalse(String username, String phone, String email);

    /**
     * 根据用户名模糊查询
     */
    Page<User> findByUsernameContainingAndIsDeletedFalse(String username, Pageable pageable);

    /**
     * 根据昵称模糊查询
     */
    Page<User> findByNicknameContainingAndIsDeletedFalse(String nickname, Pageable pageable);

    /**
     * 根据角色查询用户
     */
    Page<User> findByRoleAndIsDeletedFalse(String role, Pageable pageable);

    /**
     * 更新用户状态
     */
    @Modifying
    @Query("UPDATE User u SET u.status = ?2 WHERE u.id = ?1")
    int updateStatus(Long id, Integer status);

    /**
     * 批量更新用户状态
     */
    @Modifying
    @Query("UPDATE User u SET u.status = ?2 WHERE u.id IN ?1")
    int batchUpdateStatus(List<Long> ids, Integer status);
}